package _06hashtable;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;

class Solution {
    public List<List<String>> groupAnagrams(String[] strs) {
        List<List<String>> result = new ArrayList<>();

        int len = strs.length;
        String[] strings = new String[len];

        // 对字符串数组中的每个字符串排序后，放入另一个字符串数组
        for (int i = 0; i < len; i++) {
            byte[] bytes = strs[i].getBytes();
            Arrays.sort(bytes);
            strings[i] = new String(bytes);
        }

        for (int i = 0; i < len; i++) {
            System.out.print("\"" + strings[i] +"\"," );
        }

        //遍历新的字符串数组，将字符串相同的归类（归类操作发生在原字符串数组上）
        for (int i = 0; i < len; i++) {
            ArrayList<String> strings1 = new ArrayList<>();
            //如果为空说明已经归类
            if (strings[i] != null) {
                strings1.add(strs[i]);
                //找其他排序后相同的字符串
                for (int j = i + 1; j < len; j++) {
                    if (strings[i].equals(strings[j])) {
                        //向结果集的子集中添加原字符串数组中的字符串
                        strings1.add(strs[j]);
                        // 已归类的字符串置为空
                        strings[j] = null;
                    }
                }
            }
            if (strings1.size() != 0)
                result.add(strings1);
        }
        return result;
    }
}

public class AnagramsGroup {
    public static void main(String[] args) {

        Solution solution = new Solution();

        String[] strings = new String[]{"eat", "tea", "tan", "ate", "nat", "bat"};
        List<List<String>> lists = solution.groupAnagrams(strings);

        Iterator<List<String>> iterator = lists.iterator();
        while (iterator.hasNext()) {
            List<String> next = iterator.next();
            System.out.println(next);
        }
    }
}
